<?php

namespace App\Services;

use Yansongda\Pay\Pay;
use Yansongda\Pay\Exception\PayException;
use Illuminate\Support\Facades\Log;

class WechatPaymentService
{
    /**
     * 创建微信扫码支付订单
     *
     * @param string $outTradeNo 商户订单号
     * @param int $totalAmount 订单金额(分)
     * @param string $description 商品描述
     * @return array
     */
    public function createScanOrder($outTradeNo, $totalAmount, $description): array
    {
        try {
            $pay = Pay::wechat([
                'appid' => env('WECHAT_APPID'),
                'mch_id' => env('WECHAT_MCH_ID'),
                'key' => env('WECHAT_MCH_KEY'),
                'notify_url' => env('WECHAT_NOTIFY_URL'),
            ]);

            $result = $pay->scan([
                'out_trade_no' => $outTradeNo,
                'total_fee' => $totalAmount,
                'body' => $description,
            ]);

            // 记录支付日志
            Log::info('微信扫码支付订单创建成功', [
                'out_trade_no' => $outTradeNo,
                'result' => $result->toArray()
            ]);

            return $result->code_url;
        } catch (\Throwable $e) {
            Log::error('微信扫码支付订单创建失败', [
                'out_trade_no' => $outTradeNo,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 处理微信支付回调
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handleNotify(callable $callback)
    {
        $pay = Pay::wechat([
            'appid' => env('WECHAT_APPID'),
            'mch_id' => env('WECHAT_MCH_ID'),
            'key' => env('WECHAT_MCH_KEY'),
        ]);

        return $pay->notify(function ($message, $fail) use ($callback) {
            // 调用回调函数处理业务逻辑
            return $callback($message, $fail);
        });
    }

    /**
     * 查询订单状态
     *
     * @param string $outTradeNo 商户订单号
     * @return array
     */
    public function queryOrder(string $outTradeNo): array
    {
        try {
            $pay = Pay::wechat([
                'appid' => env('WECHAT_APPID'),
                'mch_id' => env('WECHAT_MCH_ID'),
                'key' => env('WECHAT_MCH_KEY'),
            ]);

            $result = $pay->query([
                'out_trade_no' => $outTradeNo,
            ]);

            return [
                'success' => true,
                'data' => $result->toArray()
            ];
        } catch (\Throwable $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
}
